<!DOCTYPE html>
<html lang="ch">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3.使正方形旋转</title>
</head>

<body onload="main()">
  <canvas id="glcanvas" width="640" height="480">
    你的浏览器似乎不支持或者禁用了HTML5 <code>&lt;canvas&gt;</code> 元素.
  </canvas>

  <script src="./static/js/gl-matrix-min.js"></script>

  <script>
    /**
     * 1.定义立方体顶点位置
     * 2.循环为每个顶点定义颜色
     * 3.定义三角形数组
     * 4.渲染三角形
    */

    var mat4 = glMatrix.mat4;
    var cubeRotation = 0.0;

    function main() {
      var canvas = document.getElementById('glcanvas')
      var gl = canvas.getContext("webgl")

      if (!gl) {
        alert('不支持webgl')
        return;
      }

      const vsSource = `
        attribute vec3 aVertexPosition;
        attribute vec4 aVertexColor;
      
        uniform mat4 uModelViewMatrix;
        uniform mat4 uProjectionMatrix;

        varying lowp vec4 vColor;

        void main() {
          gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aVertexPosition, 1.0);;
          vColor = aVertexColor;
        }
      `;

      const fsSource = `
        varying lowp vec4 vColor;
        void main() {
         gl_FragColor = vColor;
        }
      `;

      const shaderProgram = initShaderProgram(gl, vsSource, fsSource)

      const programInfo = {
        program: shaderProgram,
        attribLocations: {
          vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
          vertexColor: gl.getAttribLocation(shaderProgram, "aVertexColor")
        },
        uniformLocations: {
          projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
          modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
        },
      };

      var buffers = initBuffers(gl)
      var then = 0;
      // 
      function render(now) {
        now *= 0.001
        const deltaTime = now - then
        then = now

        drawScene(gl, programInfo, buffers, deltaTime)
        cubeRotation += deltaTime;

        requestAnimationFrame(render)
      }

      requestAnimationFrame(render);
    }


    // 初始化着色器
    function initShaderProgram(gl, vsSource, fsSource) {
      const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource)
      const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);

      const shaderProgram = gl.createProgram()
      gl.attachShader(shaderProgram, vertexShader)
      gl.attachShader(shaderProgram, fragmentShader)

      gl.linkProgram(shaderProgram)

      if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
        alert('初始化着色器失败')
        return null
      }
      return shaderProgram;
    }

    function loadShader(gl, type, source) {
      const shader = gl.createShader(type)
      gl.shaderSource(shader, source)
      gl.compileShader(shader)

      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert('初始化着色器失败')
        gl.deleteShader(shader);
        return null
      }
      return shader
    }


    function initBuffers(gl) {
      const positionBuffer = gl.createBuffer()
      gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)

      // 定义立方体顶点位置
      var vertices = [
        // Front face
        -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,

        // Back face
        -1.0, -1.0, -1.0,
        -1.0, 1.0, -1.0,
        1.0, 1.0, -1.0,
        1.0, -1.0, -1.0,

        // Top face
        -1.0, 1.0, -1.0,
        -1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, -1.0,

        // Bottom face
        -1.0, -1.0, -1.0,
        1.0, -1.0, -1.0,
        1.0, -1.0, 1.0,
        -1.0, -1.0, 1.0,

        // Right face
        1.0, -1.0, -1.0,
        1.0, 1.0, -1.0,
        1.0, 1.0, 1.0,
        1.0, -1.0, 1.0,

        // Left face
        -1.0, -1.0, -1.0,
        -1.0, -1.0, 1.0,
        -1.0, 1.0, 1.0,
        -1.0, 1.0, -1.0
      ]


      gl.bufferData(gl.ARRAY_BUFFER,
        new Float32Array(vertices),
        gl.STATIC_DRAW)


      const colors = [
        [1.0, 1.0, 1.0, 1.0],    // Front face: white
        [1.0, 0.0, 0.0, 1.0],    // Back face: red
        [0.0, 1.0, 0.0, 1.0],    // Top face: green
        [0.0, 0.0, 1.0, 1.0],    // Bottom face: blue
        [1.0, 1.0, 0.0, 1.0],    // Right face: yellow
        [1.0, 0.0, 1.0, 1.0]     // Left face: purple
      ]

      // 循环为每个顶点定义颜色
      var generatedColors = []

      for (let i = 0; i < 6; i++) {
        var c = colors[i];

        for (let j = 0; j < 4; j++) {
          generatedColors = generatedColors.concat(c)
        }
      }

      var cubeVerticesColorBuffer = gl.createBuffer()
      gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesColorBuffer)
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(generatedColors), gl.STATIC_DRAW)


      // 定义三角形数组
      const cubeVerticesIndexBuffer = gl.createBuffer()
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer)
      //这个数组定义每个面为两个三角形  
      //索引到顶点数组来指定每个三角形  
      var cubeVertexIndices = [
        0, 1, 2, 0, 2, 3,    // front
        4, 5, 6, 4, 6, 7,    // back
        8, 9, 10, 8, 10, 11,   // top
        12, 13, 14, 12, 14, 15,   // bottom
        16, 17, 18, 16, 18, 19,   // right
        20, 21, 22, 20, 22, 23    // left
      ]

      // 现在将元素数组发送给GL
      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
        new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW)


      return {
        position: positionBuffer,
        color: cubeVerticesColorBuffer,
        indices: cubeVerticesIndexBuffer
      }
    }


    // 渲染场景
    function drawScene(gl, programInfo, buffers) {
      gl.clearColor(0.0, 0.0, 0.0, 1.0);
      gl.clearDepth(1.0)
      gl.enable(gl.DEPTH_TEST)
      gl.depthFunc(gl.LEQUAL)

      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)


      const fieldOfView = 45 * Math.PI / 180
      const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight
      const zNear = 0.1
      const zFar = 100.0
      const projectionMatrix = mat4.create()

      mat4.perspective(projectionMatrix,
        fieldOfView,
        aspect,
        zNear,
        zFar
      )

      const modelViewMatrix = mat4.create()

      mat4.translate(modelViewMatrix,  //目的地矩阵
        modelViewMatrix, // 翻转矩阵
        [-0.0, 0.0, -6.0] // 翻转量
      )

      // 将modelViewMatrix的当前值cubeRotation绕Z轴旋转
      mat4.rotate(modelViewMatrix,
        modelViewMatrix,
        cubeRotation,
        [0, 0, 1])

      mat4.rotate(modelViewMatrix,
        modelViewMatrix,
        cubeRotation * .7,
        [1, 1, 0])


      {
        const numComponents = 3  //每次迭代提取2个值
        const type = gl.FLOAT     // buffer 类型是32bit float
        const normalize = false   // 不使用标准化
        const stride = 0           //从一组值到下一组值需要多少字节
        const offset = 0           //从缓冲区内多少字节开始  

        // setMatrixUniforms();
        // 绘制正方形时使用颜色
        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position)
        gl.vertexAttribPointer(
          programInfo.attribLocations.vertexPosition,
          numComponents,
          type,
          normalize,
          stride,
          offset
        )
        gl.enableVertexAttribArray(
          programInfo.attribLocations.vertexPosition
        )
      }

      // 初始化颜色属性
      {
        const numComponents = 4   //每次迭代提取4个值
        const type = gl.FLOAT     // buffer 类型是32bit float
        const normalize = false   // 不使用标准化
        const stride = 0           //从一组值到下一组值需要多少字节
        const offset = 0           //从缓冲区内多少字节开始  

        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color)
        // 绘制正方形时使用颜色
        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color)
        gl.vertexAttribPointer(
          programInfo.attribLocations.vertexColor,
          numComponents,
          type,
          normalize,
          stride,
          offset
        )
        gl.enableVertexAttribArray(
          programInfo.attribLocations.vertexColor
        )
      }

      // 使用立方体顶点索引数据来渲染
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices)

      gl.useProgram(programInfo.program)

      gl.uniformMatrix4fv(
        programInfo.uniformLocations.projectionMatrix,
        false,
        projectionMatrix
      )
      gl.uniformMatrix4fv(
        programInfo.uniformLocations.modelViewMatrix,
        false,
        modelViewMatrix
      )
      {
        const vertexCount = 36;
        const type = gl.UNSIGNED_SHORT;
        const offset = 0;
        gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
      }
    }
  </script>
</body>

</html>